<template>
	<div class="container">
		<h2>查看合同</h2>
		<a-form ref="formRef" :model="formState" layout="vertical" @finish="saveContract">
			<a-row :gutter="20">
				<a-col :span="12">
					<a-form-item label="合同名称" name="name" :rules="{required:true, message:'请输入合同名称'}">
						<a-input v-model:value="formState.name" disabled />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="合同编号" name="code" :rules="{required:true, message:'请输入合同编号'}">
						<a-input v-model:value="formState.code" disabled />
					</a-form-item>
				</a-col>
				<a-col :span="24">
					<a-form-item label="选择计划名称" name="plan_id" :rules="{required:true, message:'请选择计划'}">
						<a-select v-model:value="formState.plan_id" disabled :options="planlist" option-filter-prop="label" @change="choosePlan"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="选择供应商名称" name="supplier_id" :rules="{required:true, message:'请选择供应商'}">
						<a-select v-model:value="formState.supplier_id" disabled :options="userlist" option-filter-prop="label"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="客户联系人" name="contact" :rules="{required:true, message:'请输入客户联系人'}">
						<a-input v-model:value="formState.contact" disabled />
					</a-form-item>
				</a-col>
				<a-col :span="12">{{ formState.price_updown===1 ? '浮动' : '固定' }}价格</a-col>
				<a-col :span="12">
					<a :href="file_path" target="_blank">查看合同附件</a>
				</a-col>

				<a-col :span="24">
					<h4>合同物资清单</h4>
					<a-table :data-source="formState.materials" :columns="planMaterialColumns" :row-key="(record) => record.key">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', index, 'source_id']" :rules="{required:true, message:'请选择材料名称'}">
									<a-tree-select v-model:value="formState.materials[record.key].source_id" disabled :show-search="true" placeholder="请选择材料名称" allow-clear tree-default-expand-all :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id)=>changeMaterial(id, record)">
										<template #title="{label}">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', index, 'id']" :rules="{required:true, message:'请选择规格'}">
									<a-select v-model:value="formState.materials[record.key].id" disabled placeholder="请选择" :options="materialModelOptions[record.source_id] || []" allow-clear :field-names="{value:'id', label:'model'}" style="width:100%"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', index, 'unit']" :rules="{required:true, message:'请选择计量单位'}">
									<a-select v-model:value="formState.materials[record.key].unit" disabled placeholder="请选择" :options="unitOptions" :field-names="{value:'name'}" style="width:100%"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', index, 'quantity']" :rules="{required:true, message:'请输入数量'}">
									<a-input v-model:value="formState.materials[index].quantity" disabled placeholder="请输入数量" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'without_tax_subprice_base'">
								<a-form-item :name="['materials', index, 'without_tax_subprice_base']" :rules="{required:true, message:'请输入不含税信息价'}">
									<a-input v-model:value="formState.materials[index].without_tax_subprice_base" disabled placeholder="请输入不含税信息价" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'down_per'">
								<a-form-item :name="['materials', index, 'down_per']">
									<a-input v-model:value="formState.materials[index].down_per" disabled placeholder="请输入下浮率" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'up_per'">
								<a-form-item :name="['materials', index, 'up_per']">
									<a-input v-model:value="formState.materials[index].up_per" disabled placeholder="请输入上浮率" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'without_tax_subprice'">
								<a-form-item :name="['materials', index, 'without_tax_subprice']" :rules="{required:true, message:'请输入不含税单价'}">
									<a-input v-model:value="formState.materials[index].without_tax_subprice" disabled placeholder="请输入不含税单价" @change="calAmount" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'without_tax_amount'">
								<a-form-item :name="['materials', index, 'without_tax_amount']" :rules="{required:true, message:'请输入不含税总价'}">
									<a-input v-model:value="formState.materials[index].without_tax_amount" disabled placeholder="请输入不含税总价" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'memo'">
								<a-form-item :name="['materials', index, 'memo']">
									<a-input v-model:value="formState.materials[index].memo" disabled placeholder="请输入备注" />
								</a-form-item>
							</template>
						</template>
					</a-table>
				</a-col>
				<a-col :span="12">
					<a-form-item label="合同总额（不含税）" name="amount" :rules="{required:true, message:'请输入合同金额'}">
						<a-input v-model:value="formState.amount" disabled />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="增值税税率" name="tax_rate" :rules="{required:true, message:'请输入增值税税率'}">
						<a-input v-model:value="formState.tax_rate" disabled size="small" />%（增值税税额=增值税税率*合同总额（不含税））
					</a-form-item>
				</a-col>

				<a-col :span="24">
					<a-form-item label="备注" name="memo">
						<a-textarea v-model:value="formState.memo" disabled :auto-size="{minRows:4, maxRows:6}"></a-textarea>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";

//import dayjs from "dayjs";
import { post, listToTree } from "../utils";
import { useRoute } from "vue-router";
const route = useRoute();
const id = computed(() => {
	return route.params.id || 0;
});
const formState = ref({ materials: [] });
const planlist = ref([]); //	计划列表
const userlist = ref([]); // 供应商列表
const formRef = ref();
const { proxy } = getCurrentInstance();

const planMaterialColumns = [
	{
		title: "ID",
		dataIndex: "key",
		width: 60,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text + 1;
		}
	},
	{
		title: "物资名称",
		dataIndex: "name",
		width: 200,
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		width: 150,
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		width: 130,
		align: "center"
	},
	{
		title: "数量",
		dataIndex: "quantity",
		width: 100,
		align: "center"
	},
	{
		title: "不含税信息价(元)",
		dataIndex: "without_tax_subprice_base",
		width: 160,
		align: "center"
	},
	{
		title: "下浮率(%)",
		dataIndex: "down_per",
		width: 100,
		align: "center"
	},
	{
		title: "上浮率(%)",
		dataIndex: "up_per",
		width: 100,
		align: "center"
	},
	{
		title: "不含税单价(元)",
		dataIndex: "without_tax_subprice",
		width: 160,
		align: "center"
	},
	{
		title: "不含税总价(元)",
		dataIndex: "without_tax_amount",
		width: 160,
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		width: 200,
		align: "center"
	},
	{}
];
const unitOptions = ref([]);
const file_path = ref();
onMounted(() => {
	if (id.value) {
		post("contract/info", { id: id.value }).then(data => {
			data.materials = data.materials.map((d, i) => {
				d.key = i;

				const { unit, quantity, without_tax_subprice_base, down_per, up_per, without_tax_subprice, without_tax_amount, memo } = d.ContractMaterial;
				d.unit = unit;
				d.quantity = quantity;
				d.without_tax_subprice_base = without_tax_subprice_base;
				d.down_per = down_per;
				d.up_per = up_per;
				d.without_tax_subprice = without_tax_subprice;
				d.without_tax_amount = without_tax_amount;
				d.memo = memo;
				return d;
			});

			formState.value = data;
			file_path.value = data.file_fath;
		});
	}
	post("user", { is_supplier: 1 }).then(({ data }) => {
		userlist.value = data.map(d => {
			return {
				value: d.id,
				label: d.company_name || d.mobile
			};
		});
	});
	post("plan").then(({ data }) => {
		planlist.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
	});
});
const choosePlan = value => {
	const plan_id = value;
	formState.value.plan_id = plan_id;
	post("dictionary", { plan_id: plan_id }).then(data => {
		//	const { root_id: rootId } = data[0] || {};
		materialOptions.value = data;
		//获取所有规格
		post("material", { source_id: data.map(d => d.id).join(","), page_size: 10000 }).then(({ data }) => {
			materialModelOptions.value = (() => {
				const array = [];
				data.forEach(d => {
					if (!array[d.source_id]) array[d.source_id] = [];

					if (d.attr) d.model = `${d.model}（${d.attr}）`;

					array[d.source_id].push(d);
				});

				return array;
			})(data);
		});
	});
	/** 
	post("plan/info", { id: value }).then(data => {
		const materials = data.materials.map((d, i) => {
			d.key = i;
			const { unit, quantity, final_unit_price } = d.PlanMaterial;
			d.unit = unit;
			d.quantity = quantity;
			d.final_unit_price = final_unit_price;
			return d;
		});

		formState.value.materials = materials;
	});*/
};

//计算总额
const calAmount = () => {
	let amount = 0;
	formState.value.materials.forEach(d => {
		if (d.quantity <= 0) {
			d.quantity = 1;
		}
		d.without_tax_amount = d.without_tax_subprice * d.quantity;
		amount = amount + d.without_tax_amount;
	});
	formState.value.amount = amount;
};
const saveContract = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };
			if (!params.materials.length) {
				proxy.$message.error("请添加材料清单");
				return;
			}

			params.materials = JSON.stringify(
				params.materials.map(({ id, unit, quantity, without_tax_subprice_base, down_per, up_per, without_tax_subprice, without_tax_amount, memo }) => {
					return {
						id,
						unit,
						quantity,
						without_tax_subprice_base,
						down_per,
						up_per,
						without_tax_subprice,
						without_tax_amount,
						memo
					};
				})
			);

			post("contract/save", params)
				.then(() => {
					if (id.value) {
						proxy.$message.success("合同修改成功", 1);
					} else {
						proxy.$message.success("合同创建成功", 1);
					}

					closeTab("/contract");
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};

post("dictionary", { root_code: "MATERIAL_UNIT" }).then(data => {
	unitOptions.value = data;
});

const materialOptions = ref([]);

post("dictionary", { root_code: "MATERIAL_CATEGORY" }).then(data => {
	const { root_id: rootId } = data[0] || {};
	materialOptions.value = listToTree(data, rootId);

	//获取所有规格
	post("material", { source_id: data.map(d => d.id).join(","), page_size: 10000 }).then(({ data }) => {
		materialModelOptions.value = (() => {
			const array = [];
			data.forEach(d => {
				if (!array[d.source_id]) array[d.source_id] = [];

				if (d.attr) d.model = `${d.model}（${d.attr}）`;

				array[d.source_id].push(d);
			});

			return array;
		})(data);
	});
});

const materialModelOptions = ref({});

const changeMaterial = (id, record) => {
	//强制选择规格
	record.id = null;

	if (!id) return;

	post("material", { source_id: id, page_size: 10000 }).then(({ data }) => {
		materialModelOptions.value[id] = data.map(d => {
			if (d.attr) d.model = `${d.model}（${d.attr}）`;

			return d;
		});
	});
};
/**
const copyMaterialModel = record => {
	formState.value.materials.push({ ...record, key: formState.value.materials.length });
}; */

//调用父页面closeTab方法
/*
//父页面定义closeTab方法
provide("closeTab", path => {
	
});
*/
const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;

	h2 {
		font-size: 16px;
		font-weight: 600;
		line-height: 30px;
		margin-bottom: 20px;
	}

	h3 {
		line-height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-bottom: 20px;

		display: flex;
		align-items: center;

		&:before {
			content: "";
			display: block;
			width: 2px;
			height: 20px;
			background: rgb(24, 144, 255);
			margin-right: 10px;
		}
	}

	h4 {
		font-weight: 600;
		margin: 15px 0;
		line-height: 30px;
	}
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;

	.ant-form-item-explain {
		position: absolute;
		bottom: -24px;
	}
}
:deep(.ant-input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
:deep(.ant-input-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
//
:deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}
</style>
